package com.proton.carepatchtemp.activity;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;

import com.apkfuns.logutils.LogUtils;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.draw.LineSeparator;
import com.joanzapata.pdfview.PDFView;
import com.joanzapata.pdfview.listener.OnDrawListener;
import com.joanzapata.pdfview.listener.OnLoadCompleteListener;
import com.joanzapata.pdfview.listener.OnPageChangeListener;
import com.proton.carepatchtemp.R;
import com.proton.carepatchtemp.base.BaseActivity;
import com.proton.carepatchtemp.utils.FileUtils;
import com.proton.carepatchtemp.utils.Pdf.EcgDraw;
import com.proton.carepatchtemp.utils.Pdf.PdfReportDetail;
import com.proton.carepatchtemp.utils.TastyUtils;
import com.proton.carepatchtemp.utils.eventbus.MainEvent;
import com.sdsmdg.tastytoast.TastyToast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class PrePDFActivity extends BaseActivity implements OnPageChangeListener, OnLoadCompleteListener, OnDrawListener {

    private static final int FIRST_PAGE_COUNT = 4000 - 25 * 3;
    private static final int OTHER_PAGE_COUNT = 4000;
    public PdfReportDetail mRptDetail;
    BaseFont bfChinese = null;
    List<EcgDraw> lsEcgDraw = new ArrayList<>();

    String path = "";
    String dirrpt = "";
    String dirtemp = "";
    String pathPdf = "";
    String pathPng = "";
    PDFView pdfview;
    private ImageButton mBtnBack;
    //过滤1/4的数据

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_preview_pdf);
        initView();
        pdfview = findViewById(R.id.pdfview);
        mRptDetail = new PdfReportDetail(getIntent().getLongExtra("reportId", 0));
        mRptDetail.setTimePeriod(String.valueOf(getIntent().getLongExtra("timePeriod", 0)));
        initTb();
        setListener();

        if (!FileUtils.isFileExist(FileUtils.pdf, mRptDetail.getReportId() + ".pdf")) {
            TastyUtils.makeTextShort(R.string.have_no_file, TastyToast.ERROR);
        } else {
            pdfview.fromFile(new File(pathPdf))
                    .pages(0, 2, 1, 3, 3, 3)
                    .defaultPage(1)
                    .onPageChange(this)
                    .onLoad(this)
                    .onDraw(this)
                    .showMinimap(false)
                    .swipeVertical(true)
                    .enableSwipe(true)
                    .load();
        }
    }

    @Override
    protected void setListener() {
        mBtnBack.setOnClickListener(v -> {
            finish();
        });
    }

    protected void initTb() {
        try {
            path = String.valueOf(mRptDetail.getReportId());
            dirrpt = FileUtils.getDirectoryP("pdf");
            dirtemp = FileUtils.getDirectoryP("temp");
            pathPdf = dirrpt + File.separator + path + ".pdf";
            pathPng = dirtemp + File.separator + path;
        } catch (Throwable e) {
            LogUtils.e(e);
        }
    }

    @Override
    public void dealEvent(MainEvent event) {
    }

    @Override
    public void onEventMainThread(MainEvent event) {
        //dealOnEvent(event);
    }

    public List<Double> getPageNum(List<Double> data, int iPage) {
        List<Double> pageContnent = new ArrayList<>();
        if (iPage == 1) {
            if (data.size() < FIRST_PAGE_COUNT) {
                return data;
            } else {
                for (int i = 0; i < OTHER_PAGE_COUNT; i++) {
                    pageContnent.add(i, data.get(i));
                }
                return pageContnent;
            }
        } else {
            for (int i = FIRST_PAGE_COUNT + OTHER_PAGE_COUNT * (iPage - 2); i < FIRST_PAGE_COUNT + OTHER_PAGE_COUNT * (iPage - 1); i++) {
                if (i >= data.size()) {
                    return pageContnent;
                }
                pageContnent.add(i - (FIRST_PAGE_COUNT + OTHER_PAGE_COUNT * (iPage - 2)), data.get(i));
            }
            return pageContnent;
        }
    }

    /**
     * @param name    报告姓名
     * @param sex     性别
     * @param age     年龄
     * @param xinlv   平均心率
     * @param zaobo   是否早搏
     * @param shijian 历时
     */
    public void createPdf(String name, String sex, String age, String xinlv, String zaobo, String shijian) {
        Document document = new Document(PageSize.A4, 20, 20, 20, 20);
        try {
            bfChinese = BaseFont.createFont("assets/fonts/simhei.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            Font font = new Font(bfChinese, 12, Font.NORMAL);
            Font fontTitle = new Font(bfChinese, 16, Font.NORMAL);
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pathPdf));
            //PdfWriter writer = PdfWriter.get(document, new FileOutputStream("sdcard/inSequence.pdf"));
            //writer.setStrictImageSequence(true);
            document.open();
            Paragraph p1 = new Paragraph(getString(R.string.pdf_title), fontTitle);
            Chunk chunk1 = new Chunk(getString(R.string.pdf_name) + name + " ", font);
            Chunk chunk2 = new Chunk(getString(R.string.pdf_sex) + sex + " ", font);
            Chunk chunk3 = new Chunk(getString(R.string.pdf_age) + age + " ", font);
            Phrase phrase1 = new Phrase();
            phrase1.add(chunk1);
            phrase1.add(chunk2);
            phrase1.add(chunk3);
            Paragraph p2 = new Paragraph();
            p2.add(phrase1);

            Chunk chunk4 = new Chunk(getString(R.string.pdf_average_beat) + xinlv + " ", font);
            Chunk chunk5 = new Chunk(getString(R.string.early_beat) + zaobo + " ", font);
            Chunk chunk6 = new Chunk(getString(R.string.time) + shijian + " ", font);

            Phrase phrase2 = new Phrase();
            phrase2.add(chunk4);
            phrase2.add(chunk5);
            phrase2.add(chunk6);

            Paragraph p3 = new Paragraph();
            p3.add(phrase2);

            Paragraph pLine = new Paragraph();
            pLine.add(new Chunk(new LineSeparator()));

            Paragraph right = new Paragraph("滤波后 单位： 10mm/mV ,25mm/s", font);
            right.setAlignment(2);

            float[] widths = {1f, 2f};
            PdfPTable table = new PdfPTable(widths);

            writer.setPageEvent(new PdfPageHelper());

            //设置间距
            p1.setSpacingBefore(50f);
            p2.setSpacingBefore(20f);
            p3.setSpacingBefore(20f);
            pLine.setSpacingBefore(10f);
            right.setSpacingBefore(20f);
            right.setIndentationRight(10f);
            document.add(p1);
            document.add(pLine);
            document.add(p2);
            document.add(p3);
            document.add(right);
            for (int i = 0; i < lsEcgDraw.size(); i++) {
                Image imageNow = Image.getInstance(pathPng + "_" + i);
                imageNow.scalePercent(15);
                imageNow.setAlignment(1);
                document.add(imageNow);
            }
            document.add(table);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        document.close();
    }

    @Override
    public void onLayerDrawn(Canvas canvas, float pageWidth, float pageHeight, int displayedPage) {

    }

    @Override
    public void loadComplete(int nbPages) {
        //LogUtils.e("加载完成");
    }

    @Override
    public void onPageChanged(int page, int pageCount) {
        //LogUtils.e("正在翻页");
    }

    private void initView() {
        mBtnBack = findViewById(R.id.btn_back);
    }

    public Bitmap createViewBitmap(View v) {
     /*   Bitmap bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(),
                Bitmap.Config.ARGB_8888);*/
        Bitmap bitmap = Bitmap.createBitmap(3523, 4228,
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.WHITE);
        v.draw(canvas);
        return bitmap;
    }

    /*public static Bitmap convertMeasureBitmap(View view) {
        view.measure(View.MeasureSpec.makeMeasureSpec(view.getWidth(), View.MeasureSpec.EXACTLY),
                View.MeasureSpec.makeMeasureSpec(view.getHeight(), View.MeasureSpec.AT_MOST));
        return convertViewToBitmap(view, view.getMeasuredWidth(), view.getMeasuredHeight());
    }*/

  /*  public static Bitmap convertViewToBitmap(View view, int width, int height) {
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        view.draw(new Canvas(bitmap));
        return bitmap;
    }*/

 /*   public static Bitmap convertBitmap(View view) {
        return convertViewToBitmap(view, view.getWidth(), view.getHeight());
    }*/

    class PdfPageHelper extends PdfPageEventHelper {
        @Override
        public void onEndPage(PdfWriter writer, Document document) {
            super.onEndPage(writer, document);
            PdfContentByte cb = writer.getDirectContent();// 得到层
            cb.saveState();
            // 开始
            cb.beginText();
            cb.setFontAndSize(bfChinese, 5);
            // Header
            float x = document.top(-20);// 位置
            // 右
            cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, getString(R.string.pdf_di) + writer.getPageNumber() + getString(R.string.pdf_page), document.right(), x, 0);
            // Footer
            float y = document.bottom(-20);
            cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, getString(R.string.pdf_di) + writer.getPageNumber() + getString(R.string.pdf_page), document.right(), y, 0);
            cb.endText();
            cb.restoreState();
        }
    }
}
